import subprocess

import ftplib
import os


def upload_directory_ftp(ftp, path, ftp_path):
    # 切换到目标路径
    try:
        ftp.mkd(ftp_path)
    except ftplib.error_perm as e:
        print(f"Directory may already exist: {e}")
    ftp.cwd(ftp_path)

    # 遍历本地目录
    for root, dirs, files in os.walk(path):
        for filename in files:
            file_path = os.path.join(root, filename)
            with open(file_path, 'rb') as file:
                ftp.storbinary(f'STOR {filename}', file)
                print(f"succ: {file_path}")

        for dirname in dirs:
            dir_path = os.path.join(root, dirname)
            ftp_dir_path = os.path.join(ftp_path, dirname)
            upload_directory_ftp(ftp, dir_path, ftp_dir_path)


def main():
    ftp_host = '192.168.0.185'
    ftp_user = 'taro'
    ftp_pass = 'GY0HA5KEwQcR'

    source_directory = '/app/ai/data/img'
    target_directory = '/AI-NAS/img'

    with ftplib.FTP(ftp_host) as ftp:
        ftp.encoding = 'utf-8'  # 设置编码为UTF-8
        ftp.connect(ftp_host)
        ftp.login(ftp_user, ftp_pass)
        upload_directory_ftp(ftp, source_directory, target_directory)
        print("Upload completed successfully.")


if __name__ == '__main__':
    main()

